package com.eqdd.yiqidian.ui.discover.makerspace

import android.app.Activity
import android.content.Intent
import android.support.v7.widget.RecyclerView
import android.view.View
import com.bigkoo.pickerview.TimePickerView
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.IndustriesBean
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditEnterBean
import com.eqdd.yiqidian.kotlin.bottomDialog
import com.eqdd.yiqidian.ui.base.SlimBaseMultiEditActivity
import com.eqdd.yiqidian.utils.TimeUtil
import kotlinx.android.synthetic.main.activity_recyclerview.*
import org.jetbrains.anko.toast
import java.text.SimpleDateFormat
import java.util.*

/**
 * Created by jhj on 18-8-4.
 */
class IndustryTimeActivity : SlimBaseMultiEditActivity() {
    var type: Int? = -1
    var isUpper: Boolean = false
    private var data: IndustriesBean.TimeBean? = null

    override fun initBinding() {
        clearData()
        setContentView(R.layout.activity_recyclerview)
        initTopTitleBar(View.VISIBLE, "服务时间段")
        initTopRightText("确定") {
            if (checkParams()) {
                val bean = slimAdapterEx.data
                val str = """{
                        "Id":"${data?.id ?: 0}",
                        "type":"$type",
                        "startTime":"${bean[1].content}",
                        "endTime":"${bean[2].content}"
                    }"""
                val intent = Intent()
                intent.putExtra("data", str)
                intent.putExtra(Config.ID, data?.id)
                setResult(Activity.RESULT_OK, intent)
                finish()
            } else {
                toast(msg)
            }
        }
    }

    override fun initRecyclerView(): RecyclerView {
        return recyclerView
    }

    override fun itemClick(p: Int) {
        when (p) {
            0 -> {
                bottomDialog(listOf("白天", "晚上")) {
                    when (it) {
                        1 -> {
                            type = 0
                            slimAdapterEx.getDataItem(0).content = "白天"
                            slimAdapterEx.notifyItemChanged(0)
                        }
                        2 -> {
                            type = 1
                            slimAdapterEx.getDataItem(0).content = "晚上"
                            slimAdapterEx.notifyItemChanged(0)
                        }
                    }
                }
            }
            1 -> {
                isUpper = true
                openTimePicker(1, 2, false)
            }
            2 -> {
                isUpper = false
                openTimePicker(1, 2, false)
            }
        }
    }


    fun openTimePicker(startIndex: Int, endIndex: Int, isCalculate: Boolean = false) {
        val now = Calendar.getInstance()
        val sf = SimpleDateFormat("HH:mm", Locale.CHINA)
        var upDate: Date? = parseDate(slimAdapterEx.getDataItem(startIndex).content)
        var downDate: Date? = parseDate(slimAdapterEx.getDataItem(endIndex).content)
        if (isUpper) {
            now.time = upDate ?: Date()
        } else {
            now.time = downDate ?: Date()
        }
        TimePickerView
                .Builder(this, TimePickerView.OnTimeSelectListener { date, v ->
                    if (isUpper) {
                        if (downDate != null && date.after(downDate)) {
                            toast("开始时间小于结束事件，请重新选择")
                            return@OnTimeSelectListener
                        }
                        upDate = date
                        slimAdapterEx.getDataItem(startIndex).content = sf.format(date)
                        slimAdapterEx.notifyItemChanged(startIndex)
                    } else {
                        if (upDate != null && date.before(upDate)) {
                            toast("开始时间小于结束事件，请重新选择")
                            return@OnTimeSelectListener
                        }
                        downDate = date
                        slimAdapterEx.getDataItem(endIndex).content = sf.format(date)
                        slimAdapterEx.notifyItemChanged(endIndex)
                    }
                    if (upDate != null && downDate != null && isCalculate) {
                        val time = TimeUtil.calculateDate(upDate, downDate)
                        datas[endIndex + 1].content = time
                        slimAdapterEx.notifyItemChanged(endIndex + 1)
                    }

                })
                .setOutSideCancelable(true)
                .setType(booleanArrayOf(false, false, false, true, true, false))
                .setDate(now)
                .build()
                .show()
    }

    private fun parseDate(time: String?): Date? {
        if (time.isNullOrBlank()) {
            return null
        }
        val array = time?.split(":")
        val calendar = Calendar.getInstance()
        if (array != null && array.size == 2) {
            calendar.set(Calendar.HOUR_OF_DAY, array.get(0).toInt())
            calendar.set(Calendar.MINUTE, array.get(1).toInt())
            return calendar.time
        } else {
            return null
        }

    }


    override fun setEditBeans() {
        data = intent.getSerializableExtra("data") as IndustriesBean.TimeBean?
        type = data?.type
        val type = when {
            data?.type == 0 -> "白天"
            data?.type == 1 -> "晚上"
            else -> ""
        }
        datas.add(SlimEditEnterBean("服务时间", type, 0, "请选择").setNeed(true).setDeal(true))
        datas.add(SlimEditEnterBean("开始时间", data?.startTime, 1, "请选择").setNeed(true).setDeal(true))
        datas.add(SlimEditEnterBean("结束时间", data?.endTime, 2, "请选择").setNeed(true).setDeal(true))
    }
}